import React, { useState, useEffect } from 'react';
import { Box, Text } from 'ink';
import { ThemeConfig, ToolUsageStatus } from '../types';
import { toolExecutor } from '../services/toolExecutor';

interface ToolUsageIndicatorProps {
  theme: ThemeConfig;
}

const ToolUsageIndicator: React.FC<ToolUsageIndicatorProps> = ({ theme }) => {
  const [currentToolUsage, setCurrentToolUsage] = useState<ToolUsageStatus | null>(null);
  const [recentToolUsages, setRecentToolUsages] = useState<ToolUsageStatus[]>([]);

  useEffect(() => {
    // 监听工具使用状态变化
    const unsubscribe = toolExecutor.addStatusListener((status) => {
      setCurrentToolUsage(status);

      // 如果工具调用完成，添加到历史记录
      if (status.status === 'success' || status.status === 'error') {
        setRecentToolUsages(prev => {
          const updated = [status, ...prev.slice(0, 4)]; // 只保留最近5条记录
          return updated;
        });

        // 3秒后清除当前状态显示
        setTimeout(() => {
          setCurrentToolUsage(null);
        }, 3000);
      }
    });

    return unsubscribe;
  }, []);

  const getStatusIcon = (status: ToolUsageStatus['status']) => {
    switch (status) {
      case 'calling':
        return '🔧';
      case 'success':
        return '✅';
      case 'error':
        return '❌';
      default:
        return '⚙️';
    }
  };

  const getStatusText = (status: ToolUsageStatus) => {
    switch (status.status) {
      case 'calling':
        return `正在使用 ${status.mcpServerName} MCP 的 ${status.toolName} 工具`;
      case 'success':
        const duration = status.duration ? `(${status.duration}ms)` : '';
        return `${status.mcpServerName} MCP 的 ${status.toolName} 工具执行完成 ${duration}`;
      case 'error':
        return `${status.mcpServerName} MCP 的 ${status.toolName} 工具执行失败`;
      default:
        return `${status.mcpServerName} MCP 的 ${status.toolName} 工具`;
    }
  };

  const getStatusColor = (status: ToolUsageStatus['status']) => {
    switch (status) {
      case 'calling':
        return 'cyan';
      case 'success':
        return 'green';
      case 'error':
        return 'red';
      default:
        return 'white';
    }
  };

  // 如果没有当前工具使用或最近记录，不显示组件
  if (!currentToolUsage && recentToolUsages.length === 0) {
    return null;
  }

  return (
    <Box flexDirection="column" marginBottom={1}>
      {/* 当前工具使用状态 */}
      {currentToolUsage && (
        <Box justifyContent="center" marginBottom={1}>
          <Box 
            borderStyle="round" 
            borderColor={getStatusColor(currentToolUsage.status)}
            paddingX={1}
            paddingY={0}
          >
            <Text color={getStatusColor(currentToolUsage.status)}>
              {getStatusIcon(currentToolUsage.status)} {getStatusText(currentToolUsage)}
            </Text>
          </Box>
        </Box>
      )}

      {/* 最近的工具使用历史（可选显示） */}
      {!currentToolUsage && recentToolUsages.length > 0 && (
        <Box justifyContent="center">
          <Box 
            borderStyle="round" 
            borderColor="gray"
            paddingX={1}
            paddingY={0}
          >
            <Text color="gray" dimColor>
              最近使用: {getStatusIcon(recentToolUsages[0].status)} {recentToolUsages[0].mcpServerName} - {recentToolUsages[0].toolName}
            </Text>
          </Box>
        </Box>
      )}
    </Box>
  );
};

export default ToolUsageIndicator;